﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using RoboTrocity;
using RoboTrocity.Code.ObjectStates;

namespace RoboTrocity{
	class BulletPool
	{
		private const int INITIAL_BULLETS = 1000;
		private const int ADDITIONAL_SIZE = 100;
		private List<Bullet> BulletList;
		private List<Boolean> Liveness;
		private int numBullets = INITIAL_BULLETS;

		private static BulletPool StaticPool = null;

		public static BulletPool Instance {
			get {
				if (StaticPool == null) {
					StaticPool = new BulletPool();
				}
				return StaticPool;
			}
		}

		private BulletPool() {
			BulletList = new List<Bullet>(INITIAL_BULLETS);
			Liveness = new List<Boolean>(INITIAL_BULLETS);
			for (int i = 0; i < INITIAL_BULLETS; ++i) {
				Bullet bullet = new Bullet();
				
				BulletList.Add(bullet);
				Liveness.Add(false);
			}
		}

		public Bullet getNewBullet(Bullet templateBullet) {
			return getNewBullet(templateBullet.getState(typeof(BulletFlyingState)).StateSprite.ImgLoc,
				templateBullet.getState(typeof(BulletCollidingState)).StateSprite.ImgLoc);
		}

		public Bullet getNewBullet(string _flyingImg, string _collidingImg) {
			for (int i = 0; i < numBullets; ++i) {
				if (!Liveness[i]) {
					Liveness[i] = true;
					BulletList[i].addState(new BulletFlyingState(BulletList[i], new Sprite(_flyingImg)));
					BulletList[i].addState(new BulletCollidingState(BulletList[i], new Sprite(_collidingImg)));

					return BulletList[i];
				}
			}
			//no live bullets left, add more
			int returnIndex = numBullets;
			addBullets();
			Liveness[returnIndex] = true;
			BulletList[returnIndex].addState(new BulletFlyingState(BulletList[returnIndex], new Sprite(_flyingImg)));
			BulletList[returnIndex].addState(new BulletCollidingState(BulletList[returnIndex], new Sprite(_collidingImg)));

		
			return BulletList[returnIndex];
		}

		private void addBullets() {
			for (int i = 0; i < ADDITIONAL_SIZE; ++i) {
				BulletList.Add(new Bullet());
				Liveness.Add(false);
			}
			numBullets += ADDITIONAL_SIZE;
		}

		public void finishUsingBullet(Bullet b) {
			int bulletIndex = BulletList.IndexOf(b);
			if (bulletIndex >= 0) {
				Liveness[bulletIndex] = false;
			}
		}

	}
}
